<template>
  <view class="container">
    <view class="bill-detail-box">
      <view class="bill-detail-item" v-if="status === 'edit'"> 车辆费用单号： {{ options.businesCode }}</view>

      <view class="bill-detail-content">
        <ve-form ref="formRef" :model="form" :rules="rules">
          <template v-if="status === 'new' || options.installment === '1'">
            <template v-for="(item, index) in form.listData" :key="item.id">
              <ve-card
                :title="'期数：' + item.payableNumStr"
                :typeIsNoneClassName="item.settlementStatusStr === '待结算' ? 'yellow' : 'blue'"
                fold
                v-model:initFold="item.initFold"
                :close="status === 'new' || item.settlementStatusStr === '已结算' ? false : showDeleteFn(item)"
                @close="() => onClose(item, index)"
              >
                <template #status>
                  <view class="card__status" :class="item.settlementStatusStr === '待结算' ? 'card-yellow' : ''">
                    {{ item.payableStatusName || item.settlementStatusStr }}
                  </view>
                </template>

                <ve-cell label="应付款日" v-if="status === 'new' || item.settlementStatusStr === '已结算'">
                  {{ item.payableTimeStr }}
                </ve-cell>
                <ve-form-item v-else label="应付款日" :prop="`listData.${index}.payableTimeStr`">
                  <ve-date-picker v-model="item.payableTimeStr" mode="date" placeholder="请选择应付款日" />
                </ve-form-item>

                <ve-cell label="每期应付金额" v-if="status === 'new' || item.settlementStatusStr === '已结算'">
                  {{ item.payableAmount || '-' }} 元
                </ve-cell>
                <ve-form-item v-else label="每期应付金额" unit="元" :prop="`listData.${index}.payableAmount`">
                  <ve-input v-model="item.payableAmount" placeholder="请输入每期应付金额" />
                </ve-form-item>

                <ve-cell label="每期实付金额" v-if="status === 'new' || item.settlementStatusStr === '已结算'">
                  {{ item.paymentAmount || '-' }} 元
                </ve-cell>
                <ve-form-item v-else label="每期实付金额" unit="元"> - </ve-form-item>

                <ve-cell label="完成付款时间" v-if="status === 'new' || item.settlementStatusStr === '已结算'">
                  {{ item.paymentTime || '-' }}
                </ve-cell>
                <ve-form-item v-else label="完成付款时间"> - </ve-form-item>

                <ve-cell label="备注" v-if="status === 'new' || item.settlementStatusStr === '已结算'">
                  {{ item.billRemark || '-' }}
                </ve-cell>
                <ve-form-item v-else label="备注" :borderBottom="false" labelPosition="top">
                  <ve-input type="textarea" v-model="item.billRemark" placeholder="请输入" />
                </ve-form-item>
              </ve-card>
              <ve-button
                type="plain"
                size="long"
                style="margin-bottom: 24rpx"
                @click="() => addStages(item)"
                v-if="showAdd(item) && usePermission('svmsapp:car-manage.add-bill')"
              >
                添加新期数
              </ve-button>
            </template>
          </template>
          <template v-if="options.installment === '0'">
            <ve-card>
              <template
                v-if="
                  noInstalment.feeNameId === 59 ||
                  noInstalment.feeNameId === 58 ||
                  noInstalment.feeNameId === 60 ||
                  noInstalment.feeNameId === 61
                "
              >
                <ve-form-item :label="noInstalment.feeName">
                  <ve-input v-model="noInstalment.totalAmount" placeholder="请输入" />
                </ve-form-item>
                <ve-form-item label="收支类型" :borderBottom="false">
                  <ve-picker-inline v-model="noInstalment.costType" placeholder="请选择收支类型" :range="repairList"> </ve-picker-inline>
                </ve-form-item>
              </template>
              <template v-else>
                <ve-form-item label="合同总金额" :borderBottom="false">
                  <ve-input v-model="noInstalment.totalAmount" placeholder="请输入" />
                </ve-form-item>
              </template>
            </ve-card>
          </template>
        </ve-form>
      </view>
    </view>
  </view>

  <ve-modal title="保存分期账单" v-model="billPlanVisiable" @cancel="onBillPlanCancel" @confirm="onBillPlanConfirm">
    <view class="confirm-content">
      <!-- 首尾款变化提示 -->
      <view class="confirm-item" v-if="confirmData.initialAmount?.change || confirmData.balanceAmount?.change">
        <view class="confirm-item-title">{{ getInitialOrBalanceAmountChangeTitleFn() }}</view>
        <view class="confirm-item-content">
          <view class="compare compare-left">
            <view class="compare-title">修改前</view>
            <view class="compare-content">
              <view class="change-item" v-if="confirmData.initialAmount.change">
                <span class="change-item-title">首款：</span>
                <span class="change-item-value">{{ addUnit(confirmData.initialAmount.prev, '元') }}</span>
              </view>
              <view class="change-item" v-if="confirmData.balanceAmount.change">
                <span class="change-item-title">尾款：</span>
                <span class="change-item-value">{{ addUnit(confirmData.balanceAmount.prev, '元') }}</span>
              </view>
            </view>
          </view>
          <view class="compare compare-right">
            <view class="compare-title">修改后</view>
            <view class="compare-content">
              <view class="change-item" v-if="confirmData.initialAmount.change">
                <span class="change-item-title">首款：</span>
                <span class="change-item-value">{{ addUnit(confirmData.initialAmount.now, '元') }}</span>
              </view>
              <view class="change-item" v-if="confirmData.balanceAmount.change">
                <span class="change-item-title">尾款：</span>
                <span class="change-item-value">{{ addUnit(confirmData.balanceAmount.now, '元') }}</span>
              </view>
            </view>
          </view>
        </view>
      </view>
      <a-divider style="margin: 20px 0 16px" v-if="confirmData.totalAmount?.change" />
      <!-- 总金额变化提示 -->
      <view class="confirm-item" v-if="confirmData.totalAmount?.change">
        <view class="confirm-item-title">账单总金额发生变化，是否要保存？</view>
        <view class="confirm-item-content">
          <view class="compare compare-left">
            <view class="compare-title">修改前</view>
            <view class="compare-content">
              <view class="change-item">
                <span class="change-item-title">账单总金额：</span>
                <span class="change-item-value">{{ addUnit(confirmData.totalAmount.prev, '元') }}</span>
              </view>
            </view>
          </view>
          <view class="compare compare-right">
            <view class="compare-title">修改后</view>
            <view class="compare-content">
              <view class="change-item">
                <span class="change-item-title">账单总金额：</span>
                <span class="change-item-value">{{ addUnit(confirmData.totalAmount.now, '元') }}</span>
              </view>
            </view>
          </view>
        </view>
      </view>
      <a-divider style="margin: 20px 0 16px" v-if="confirmData.lnstalmentNum?.change" />
      <!-- 分期期数变化提示 -->
      <view class="confirm-item" v-if="confirmData.lnstalmentNum?.change">
        <view class="confirm-item-title">分期期数发生变化，是否要保存？</view>
        <view class="confirm-item-content">
          <view class="compare compare-left">
            <view class="compare-title">修改前</view>
            <view class="compare-content">
              <view class="change-item">
                <span class="change-item-title">账单期数：</span>
                <span class="change-item-value">{{ addUnit(confirmData.lnstalmentNum.prev, '期') }}</span>
              </view>
            </view>
          </view>
          <view class="compare compare-right">
            <view class="compare-title">修改后</view>
            <view class="compare-content">
              <view class="change-item">
                <span class="change-item-title">账单期数：</span>
                <span class="change-item-value">{{ addUnit(confirmData.lnstalmentNum.now, '期') }}</span>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </ve-modal>

  <ve-bottom-box size="mini" v-if="status === 'edit' && payableStatus">
    <ve-button type="primary" size="long" @click="onSubmit">确认修改</ve-button>
  </ve-bottom-box>
</template>
<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { getBillPlan, findPayableListById, getLendCostList } from '@/api/asset/car-manager'
  import { updateAssetFeePlan, getPurchaseFeeDetailNoStage, updatePurchaseFeeDetailNoStage } from '@/api/asset/asset-fee'
  import { onLoad } from '@dcloudio/uni-app'
  import decimal from '@/utils/calculation'
  import { usePermission } from '@/hooks/usePermission'

  const payableStatus = ref(true)
  const billPlanVisiable = ref(false)
  const status = ref('new')
  const formRef = ref()
  const form = reactive<any>({
    listData: [],
  })
  const rules = computed(() => {
    const _rules: any = {}
    form.listData.forEach((item: any, index: number) => {
      _rules[`listData.${index}.payableTimeStr`] = {
        required: true,
        message: '请选择',
      }
      _rules[`listData.${index}.payableAmount`] = {
        required: true,
        message: '请输入',
      }
    })
    return _rules
  })
  const repairList = [
    { value: 0, label: '收款' },
    { value: 1, label: '付款' },
  ]

  const onClose = (record: any, index: number) => {
    // 已确认付款数量
    let paymentNum = 0
    // 获取期数最大值
    let max = 0
    form.listData.forEach((item: any) => {
      if (item.payableStatus == 'paid') {
        paymentNum += 1
      }
      if (item.payableNum >= max) {
        max = item.payableNum
      }
    })

    if (max === paymentNum || record.payableNum == 1) {
      uni.showToast({
        title: `请至少保留一期`,
        icon: 'none',
      })
    } else {
      form.listData.splice(index, 1)
    }
  }

  const showDeleteFn = (record: any) => {
    console.log('showDeleteFn', record)
    // 获取最大的期数（首期为-1 尾期为-2）
    let max = 0
    form.listData.forEach((item: any) => {
      if (item.payableNum >= max) {
        max = item.payableNum
      }
    })

    if (form.listData.length > 1) {
      if (record.payableNum == max && record.payableStatus !== 'paid') {
        return true
      }
    }
    if ((record.payableNum == -2 || record.payableNum == -1) && record.payableStatus !== 'paid') {
      return true
    }
    return false
  }

  const addStages = (record: any) => {
    console.log('addStages', record)
    // 应付款日
    let payableTimeStr = record.payableTimeStr
    // 付款金额
    let payableAmount = record.payableAmount
    if (!payableTimeStr || !payableAmount) {
      let payableNumStr = record.payableNumStr
      let noInput = ''
      if (!payableTimeStr && !payableAmount) {
        noInput = '应付款日和每期应付金额'
      } else {
        noInput = !payableTimeStr ? '应付款日' : '每期应付金额'
      }
      uni.showToast({
        title: `请录入${payableNumStr}${noInput}`,
        icon: 'none',
      })
      return
    }
    let tableVal = form.listData
    // 由于添加新分期在 最后一期上（不是尾期），所以新分期的 payableNum 值为当前分期 + 1
    let payableNum = record.payableNum + 1
    let payableNumStr = `第${payableNum}期`
    // 存在尾期
    let newTableItem = {
      payableNum,
      payableNumStr,
      settlementStatusStr: '待结算',
      payableStatusName: '未付款',
      contractId: contractInfo.value,
    }
    // 存在尾期
    if (tableVal.some((item: any) => item.payableNum == -2)) {
      form.listData.splice(payableNum, 0, newTableItem)
    } else {
      form.listData.push(newTableItem)
    }
  }

  const showAdd = (record: any) => {
    let max = -1
    form.listData.forEach((item: any) => {
      if (item.payableNum >= max) {
        max = item.payableNum
      }
    })
    if (record.payableNum == max && status.value === 'edit' && record.payableStatus !== 'paid') {
      return true
    }
    return false
  }

  const getInitialOrBalanceAmountChangeTitleFn = () => {
    if (confirmData.value.initialAmount?.change && confirmData.value.balanceAmount?.change) {
      return '首款/尾款金额发生变化，是否要保存？'
    } else {
      if (confirmData.value.initialAmount?.change) {
        return '首款金额发生变化，是否要保存？'
      }
      if (confirmData.value.balanceAmount?.change) {
        return '尾款金额发生变化，是否要保存？'
      }
    }
  }

  const addUnit = (val: any, unit: any) => {
    if (val != '删除') {
      if (unit == '元') {
        return (+val).toFixed(2) + ' ' + unit
      } else {
        return val + ' ' + unit
      }
    }
    return val
  }

  const onBillPlanCancel = () => {
    billPlanVisiable.value = false
  }

  const onBillPlanConfirm = () => {
    saveApi()
  }

  const saveApi = () => {
    let list = form.listData
    let tempList = list.map((item: any) => {
      let payableTime = item.payableTimeStr.replace(/\//g, '-') + ' 00:00:00'
      return {
        id: item.id,
        payableNum: item.payableNum,
        payableTime: payableTime,
        payableAmount: item.payableAmount,
        billRemark: item.billRemark,
        contractId: item.contractId,
      }
    })

    updateAssetFeePlan(tempList)
      .then(() => {
        uni.navigateBack()
      })
      .catch((err: any) => {
        uni.showToast({
          title: err.data.message,
          icon: 'none',
        })
      })
  }

  // 获取分期数
  const getInstalmentNum = (data: any) => {
    return data.filter((item: any) => item.payableNum != -1 && item.payableNum != -2).length
  }

  const confirmData = ref()
  const onSubmit = () => {
    if (options.value.installment === '1') {
      formRef.value.validate((valid: any, errors: any) => {
        if (valid) {
          // 判断必填项是否书写 start
          let nowData = form.listData
          // 判断日期是否小于首期付款日
          // 从第2期开始判断，第1期时间不做限制，可以比首期时间早
          for (let i = 1; i < nowData.length; i++) {
            let nowItem: any = nowData[i]
            let payableNum = nowItem.payableNum
            if (payableNum == 1) {
              continue
            }
            if (payableNum == -2) {
              continue
            }
            let prevItem: any = nowData[i - 1]
            let nowTime = nowItem.payableTimeStr
            let nowTStamp = new Date(nowTime).getTime()
            let prevTime = prevItem.payableTimeStr
            let prevTStamp = new Date(prevTime).getTime()
            if (nowTStamp < prevTStamp) {
              return uni.showToast({
                title: `${nowItem.payableNumStr}应付款日需大于等于上一期的应付款日`,
                icon: 'none',
              })
            }
          }
          // 判断日期是否后面日期超过前面日期
          let prevData = prevRecordData
          // 变化的数量
          let changedNumber = 0
          // 1 首款/尾款是否有变化
          // 首款
          let initialAmount: any = {
            change: false,
          }
          if (prevData.some((item: any) => item.payableNum == -1)) {
            initialAmount.prev = prevData[0].payableAmount
            if (nowData.some((item: any) => item.payableNum == -1)) {
              initialAmount.now = nowData[0].payableAmount
            } else {
              initialAmount.now = '删除'
            }
            let changedAmount = initialAmount.prev != initialAmount.now
            if (changedAmount) {
              initialAmount.change = changedAmount
              changedNumber += 1
            }
          }
          // 尾款
          let balanceAmount: any = {
            change: false,
          }
          if (prevData.some((item: any) => item.payableNum == -2)) {
            balanceAmount.prev = prevData[prevData.length - 1].payableAmount
            if (nowData.some((item: any) => item.payableNum == -2)) {
              balanceAmount.now = nowData[nowData.length - 1].payableAmount
            } else {
              balanceAmount.now = '删除'
            }
            let changedBalanceAmount = balanceAmount.prev != balanceAmount.now
            if (changedBalanceAmount) {
              balanceAmount.change = changedBalanceAmount
              changedNumber += 1
            }
          }
          // 2 账单总金额同车辆详情中设置的合同总金额是否有出入
          let totalAmount = {
            change: false,
            prev: 0,
            now: 0,
          }
          let prevSum = 0
          prevData.forEach((item: any) => {
            prevSum += decimal.add(item.payableAmount)
          })
          let nowSum = 0
          nowData.forEach((item: any) => {
            nowSum += decimal.add(item.payableAmount)
          })
          totalAmount.prev = prevSum
          totalAmount.now = nowSum
          let changedTotalAmount = prevSum != nowSum
          if (changedTotalAmount) {
            totalAmount.change = changedTotalAmount
            changedNumber += 1
          }
          // 3 期数是否有变化
          let prevInstalmentNum = getInstalmentNum(prevData)
          let nowInstalmentNum = getInstalmentNum(nowData)
          let lnstalmentNum = {
            change: false,
            prev: prevInstalmentNum,
            now: nowInstalmentNum,
          }
          let changedInstalmentNum = prevInstalmentNum != nowInstalmentNum
          if (changedInstalmentNum) {
            lnstalmentNum.change = true
            changedNumber += 1
          }
          if (changedNumber > 0) {
            console.log('修改了付款计划，需要二次确认')
            confirmData.value = {
              initialAmount,
              balanceAmount,
              totalAmount,
              lnstalmentNum,
            }
            console.log(confirmData.value, 'confirmData')
            billPlanVisiable.value = true
          } else {
            saveApi()
          }
        } else {
          console.log('error', errors)
        }
      })
    }

    if (options.value.installment === '0') {
      updatePurchaseFeeDetailNoStage({
        businesId: options.value.id,
        feeCategory: 0,
        totalAmount: noInstalment.value.totalAmount,
        costType: noInstalment.value.costType,
        id: options.value._id,
      }).then(() => {
        uni.navigateBack()
      })
    }
  }

  const contractInfo = ref()
  onMounted(() => {
    if (status.value === 'new') {
      uni.setNavigationBarTitle({
        title: '查看账单计划',
      })
    } else {
      uni.setNavigationBarTitle({
        title: '修改账单计划',
      })
    }

    uni.$once('viewContractInfoNoId', (value) => {
      console.log('viewContractInfoNoId', value)
      contractInfo.value = value
      getBillPlan(value).then((res) => {
        console.log('getBillPlan', res)
        form.listData = res.result
      })
    })
  })

  let prevRecordData: any = null
  const options = ref()
  const noInstalment = ref<any>({
    totalAmount: '',
  })
  onLoad((option: any) => {
    console.log('option', option)

    options.value = option // 保存参数

    if (option.status) {
      status.value = option.status
    }
    if (option.id) {
      contractInfo.value = option.id

      // 分期账单详情
      if (option.installment === '1') {
        if (option.feeNameId === 59) {
          getLendCostList({ id: option.id }).then((res: any) => {
            form.listData = res.result
            prevRecordData = JSON.parse(JSON.stringify(res.result))
          })
        } else {
          findPayableListById({ id: option.id }).then((res) => {
            console.log('findPayableListById', res)
            form.listData = res.result
            prevRecordData = JSON.parse(JSON.stringify(res.result))
          })
        }
      }
      // 不分期账单详情
      if (option.installment === '0') {
        getPurchaseFeeDetailNoStage({ businesId: option.id, feeCategory: option.feeCategory, id: option._id }).then((res: any) => {
          console.log('getPurchaseFeeDetailNoStage', res)
          const result = res.result
          noInstalment.value = result[0]
        })
      }

      if (!option.installment) {
        findPayableListById({ id: option.id }).then((res) => {
          console.log('findPayableListById', res)
          form.listData = res.result
          prevRecordData = JSON.parse(JSON.stringify(res.result))
        })
      }
    }
  })
</script>
<style scoped lang="less">
  .header {
    position: relative;
    height: 88rpx;
    background: #ffffff;
    text-align: center;

    .back-btn {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 24px;
    }
  }

  .ve-bottom-box {
    height: 132rpx;
  }

  .card__status {
    width: 104rpx;
    height: 40rpx;
    background: #3491fa;
    border-radius: 792rpx 792rpx 792rpx 792rpx;
    font-size: 24rpx;
    font-weight: 500;
    color: #ffffff;
    line-height: 40rpx;
    text-align: center;
    margin-left: 16rpx;
  }

  .card-yellow {
    background-color: rgba(255, 125, 0, 1);
  }

  .container {
    height: auto;
    background: #f7f8fa;
    .bill-detail-box {
      padding: 24rpx 24rpx;
    }
    .bill-detail-item {
      margin-bottom: 24rpx;
      display: flex;
      flex-wrap: wrap;
      font-size: 32rpx;
      font-weight: 600;
      color: #191c27;
      word-break: break-all;
      margin-bottom: 24rpx;
    }
  }

  :deep(.ve-cell-content) {
    word-break: break-all;
  }

  :deep(.ve-modal-body) {
    padding-bottom: 24rpx;
  }
  .confirm-item-title {
    font-size: 14px;
    color: #165dff;
    font-weight: 600;
    text-align: center;
    margin: 20px 0 10px;
  }
  .confirm-item:first-of-type {
    .confirm-item-title {
      margin-top: 0;
    }
  }
  .confirm-tips {
    color: #ff5b60;
    text-align: center;
    font-size: 14px;
    margin-bottom: 10px;
  }
  .confirm-item-content {
    .compare {
      padding: 20px;
      width: calc(50% - 8px);
      display: inline-block;
    }
    .compare + .compare {
      margin-left: 16px;
    }
    .change-item + .change-item {
      margin-top: 8px;
    }
    .compare-left {
      background: #fbfbfc;
    }
    .compare-right {
      background: rgba(22, 93, 255, 0.05);
    }
    .compare-title {
      color: #1d2129;
      margin-bottom: 10px;
    }
    .change-item-title {
      color: #4e5969;
    }
    .change-item-value {
      color: #1d2129;
    }
  }

  .ve-card:last-child {
    margin-bottom: 0;
  }

  .operate-list {
    padding-bottom: 20rpx;
  }
</style>
